<?php
App::uses('AppController', 'Controller');
/**
 * Users Controller
 *
 * @property User $User
 * @property PaginatorComponent $Paginator
 */
class UsersController extends AppController {

/**
 * Components
 *
 * @var array
 */
	public $components = array('Paginator');

	public function beforeFilter(){
		parent::beforeFilter();
		$this->Auth->allow('admin_login','login','logout','register','forget','valid','reset','reseted');
	}
/**
 * index method
 *
 * @return void
 */
	public function index() {
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $this->Auth->user('id')));
		$user = $this->User->find('first', $options);
		$this->set('user',$user);
		
		$SITEID = Configure::read('SITEID');
		// 热门推荐-------------------------------------------------------------
		$this->loadModel('Ticket');
		$hotTicket = $this->Ticket->find('all',array(
				'conditions'=>array(
						'Ticket.sort_top'=>1,
						'Ticket.sys_website_id'=>$SITEID
				),
				'order'=>'Ticket.sort DESC',
				'limit'=>10
		));
		$this->set('hotTicket',$hotTicket);
	}

/**
 * view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function view($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
		$this->set('user', $this->User->find('first', $options));
	}

/**
 * add method
 *
 * @return void
 */
	public function add() {
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		}
		$userGroups = $this->User->UserGroup->find('list');
		$this->set(compact('userGroups'));
	}

/**
 * edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function info() {
		$id = $this->Auth->user('id');
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->User->id = $id;
		if ($this->request->is(array('post', 'put'))) {
			 $checkEmail = $this->User->find('count',array(
					'conditions'=>array(
						'User.email'=>$this->request->data['User']['email'],
						'User.id <>'=>$id
					)
			));
			 $checkMobile = $this->User->find('count',array(
			 		'conditions'=>array(
			 				'User.mobile'=>$this->request->data['User']['mobile'],
			 				'User.id <>'=>$id
			 		)
			 ));
			if($checkEmail){
				$this->Session->setFlash('邮箱已存在！','tip/tip_uc');
			}elseif ($checkMobile){
				$this->Session->setFlash('手机号码已存在！','tip/tip_uc');
			}else if ($this->User->save($this->request->data)) {
				$this->Session->setFlash('保存成功！','tip/tip_uc');
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash('保存失败！','tip/tip_uc');
			}
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$fullUser = $this->User->find('first', $options);
			$this->request->data['User']['sys_photo_id'] = $fullUser['User']['sys_photo_id'];
			$this->request->data['SysPhoto'] = $fullUser['SysPhoto'];
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $this->User->find('first', $options);
		}
	}

/**
 * delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function delete($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->User->delete()) {
			$this->Session->setFlash(__('The user has been deleted.'));
		} else {
			$this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}

	/**
	 * function
	 * @author mingxing.zhao@qq.com
	 * @date 2013-12-21 下午4:55:11
	 * @param variable
	 * @return 
	 */
	public function admin_index() {
		$this->User->recursive = 0;
		$this->loadModel('UserState');
		$this->set('userstate',$this->UserState->find('list'));
		$action = array('admin' => true,'controller' => 'Users','action'=>'jsonPage');
		$param = $this->User->pageParam($action);
		$this->set('paginationScript',$this->User->showGridPagination($param));
	}
	
	/**
	 * function
	 * @author mingxing.zhao@qq.com
	 * @date 2013-12-21 下午5:05:53
	 * @param variable
	 * @return 
	 */
	function admin_jsonPage($type = false){
		$this->User->recursive = -1;
		$this->autoRender = false;
		$searchtype = $this->request->data('_search');
		$conditions = array();
		if($searchtype=='true'){
			$conditions = $this->search_condition($this->request->data);
		}
		//type 1:系统管理员;2:管理员;else:会员;
		if($type == '1'){//管理员
			$conditions['User.user_group_id']= 1;
		}else if($type=='2'){
			$conditions['User.user_group_id >']= 2;
		}else{
			$conditions['User.user_group_id']= 2;
		}
	
		$config = array(
				'_search'=>$searchtype,
				'page'=>$this->request->data('page'),
				'rows'=>$this->request->data('rows'),
				'sidx'=>$this->request->data('sidx'),
				'sord'=>$this->request->data('sord')
		);
		$res = $this->User->pagination($config,array(),$conditions);
		return $this->User->jsonData($res);
	}
	/**
	 * 查询条件
	 * @author zmx@gootop.net
	 * @Date 2011-2-23
	 * @return
	 */
	private function search_condition($param){
		$this->User->recursive = 0;
		$search['User'] = $param['User'];
		$c = $this->postConditions($search);
		$return = array();
		if($c['User.username'] != ''){
			$return['or'] = array(
					array('User.username like' =>'%'.$c['User.username'].'%'),
			);
		}
		if($c['User.email'] != ''){
			$return['User.email']= $c['User.email'];
		}
		if($c['User.mobile'] != ''){
			$return['User.mobile']= $c['User.mobile'];
		}
		if($c['User.user_state_id'] > 0){
			$return['User.user_state_id']= $c['User.user_state_id'];
		}
		if($c['User.from'] !='' && $c['User.to'] !=''){
			$return['AND']['User.created >=']= $c['User.from'];
			$return['AND']['User.created <=']= $c['User.to'].' 23:59:59';
		}else if($c['User.from'] !=''){
			$return['User.created >=']= $c['User.from'];
		}else if($c['User.to'] !=''){
			$return['User.created <=']= $c['User.to'].' 23:59:59';
		}
		return $return;
	}

/**
 * admin_view method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_view($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
		$this->set('user', $this->User->find('first', $options));
	}

/**
 * admin_add method
 *
 * @return void
 */
	public function admin_add() {
		if ($this->request->is('post')) {
			$this->User->create();
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		}
		$userGroups = $this->User->UserGroup->find('list');
		$this->set(compact('userGroups'));
	}

/**
 * admin_edit method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_edit($id = null) {
		if (!$this->User->exists($id)) {
			throw new NotFoundException(__('Invalid user'));
		}
		if ($this->request->is(array('post', 'put'))) {
			if ($this->User->save($this->request->data)) {
				$this->Session->setFlash(__('The user has been saved.'));
				return $this->redirect(array('action' => 'index'));
			} else {
				$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		} else {
			$options = array('conditions' => array('User.' . $this->User->primaryKey => $id));
			$this->request->data = $this->User->find('first', $options);
		}
		$userGroups = $this->User->UserGroup->find('list');
		$this->set(compact('userGroups'));
	}

/**
 * admin_delete method
 *
 * @throws NotFoundException
 * @param string $id
 * @return void
 */
	public function admin_delete($id = null) {
		$this->User->id = $id;
		if (!$this->User->exists()) {
			throw new NotFoundException(__('Invalid user'));
		}
		$this->request->onlyAllow('post', 'delete');
		if ($this->User->delete()) {
			$this->Session->setFlash(__('The user has been deleted.'));
		} else {
			$this->Session->setFlash(__('The user could not be deleted. Please, try again.'));
		}
		return $this->redirect(array('action' => 'index'));
	}

	/**
	 * admin_login
	 * 
	 * @auth iamcoding@qq.com
	 */
	public function admin_login() {
		$this->layout = false;
		if ($this->request->is('post')) {
			$this->Auth->autoRedirect = false;
			$userLogin = $this->User->userLogin($this->request->data);
			if($userLogin){
				$this->Auth->login($userLogin['User']);
			}
			if ($this->Auth->loggedIn()) {//login auth
				$SITEID = $this->request->data['User']['SITEID'];
				if($this->Auth->user('user_group_id')>2){//group check
					if($this->Auth->user('user_state_id')==1){//user state check
						$this->Session->Write('SITEID', $SITEID);
						$this->redirect(array('admin'=>true,'controller'=>'Index','action'=>'index'));
					}else{
						$this->Auth->logout();
						$this->Session->setFlash('您的账户已被限制','tip/tip');
					}
				}else if($this->Auth->user('user_group_id') == 1){
					$this->Session->Write('SITEID', $SITEID);
					$this->redirect(array('admin'=>true,'controller'=>'Index','action'=>'index'));
				}else{
					$this->Auth->logout();
					$this->Session->setFlash('权限不足','tip/tip',array('t'=>'error'));
					$this->redirect(array('admin'=>true,'controller'=>'users','action'=>'login'));
				}
			} else {
				$this->Session->setFlash('用户名或密码不正确.','tip/tip');
			}
		}
	}
	
	public function admin_password(){
	
		$this->User->id = $this->Auth->user('id');
		if (! $this->User->exists ()) {
			throw new NotFoundException ( __( 'Invalid user' ) );
		}
		if ($this->request->is ( 'post' ) || $this->request->is ( 'put' )) {
			if ($this->User->editAdminPassword($this->request->data)) {
				$this->Session->setFlash(__( 'The user has been saved'),'tip/tip_float',array('t'=>'success') );
				$this->request->data['User'] = $this->Auth->user();
			} else {
				$this->Session->setFlash(__( 'The user could not be saved. Please, try again.' ),'tip/tip_float' );
			}
		} else{
			$this->request->data['User'] = $this->Auth->user();
		}
	}
	
	public function admin_logout(){
		$this->Session->setFlash('您已安全退出系统','tip/tip',array('t'=>'info'));
		$this->Auth->logout();
		$this->redirect(array('admin'=>true,'controller'=>'users','action'=>'login'));
	}
	
	public function login() {
		if ($this->request->is('post')) {
			$this->Auth->autoRedirect = false;
			$sessioncode = $this->Session->read('login_code');
			$authcode = md5(strtolower($this->request->data['User']['authcode']));
			if($sessioncode != $authcode){
				$this->Session->setFlash('验证码不正确.','tip/tip_uc');
			}else{
				$userLogin = $this->User->userLogin($this->request->data);
				if($userLogin){
					$this->Auth->login($userLogin['User']);
				}
				if ($this->Auth->loggedIn()) {//login auth
					if($this->Auth->user('user_group_id') == 2){
						if($this->Auth->user('user_state_id')==1){//user state check
							$this->redirect(citylink('Users'));
						}else{
							$this->Auth->logout();
							$this->Session->setFlash('您的账户已被限制','tip/tip_uc');
						}
						 
					}else{
						$this->Auth->logout();
						$this->Session->setFlash('权限不足','tip/tip_uc',array('t'=>'error'));
						$this->redirect(citylink('Users','login'));
					}
				} else {
					$this->Session->setFlash('用户名或密码不正确.','tip/tip_uc');
				}
			}
		}
		$this->set('seo_title','会员登录');
		$this->set('seo_keywords',false);
		$this->set('seo_description',false);
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}
	
	public function logout(){
		//$this->Session->setFlash('您已安全退出系统','tip/tip',array('t'=>'info'));
		$this->Auth->logout();
		$this->redirect(array('controller'=>'Index','action'=>'index'));
	}
	
	public function register() {
		if ($this->request->is('post')) {
			$save = $this->User->register($this->request->data,2);
			if ($save) {
				//$this->Session->setFlash(__('The user has been saved.'));
				$user = $this->User->findById($save);
				$this->Auth->login($user['User']);
				return $this->redirect(array('controller'=>'Users','action' => 'index'));
			} else {
			//	$this->Session->setFlash(__('The user could not be saved. Please, try again.'));
			}
		}
		$this->set('seo_title','会员注册');
		$this->set('seo_keywords',false);
		$this->set('seo_description',false);
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}
	
	public function forget() {
		$this->Session->delete('forget.email');
		if ($this->request->is(array('post', 'put'))) {
			$data = $this->request->data;
			$email = $data['User']['email'];
			$code = $data['User']['authcode'];
			$forgetpwd_code = !empty($_SESSION['forgetpwd_code'])?$_SESSION['forgetpwd_code']:'';
			if(md5(strtolower($code)) != $forgetpwd_code){
				$this->Session->setFlash('验证码不正确!','tip/tip_uc',array('t'=>'error'));
			}else{
				$userInfo = $this->User->find ('first',array(
						'conditions' => array('User.email'=>$email)));//会员组
				if($userInfo){
					$this->Session->write('forget.email',$email);
					
					$SITEID = 1;//$this->Session->read('SITEID');
					$file = new File(TMP.DS.'cache'.DS.'config'.$SITEID);
					$config = unserialize($file->read());
					if(!$config['Setting']['mail_state']){
						$this->Session->setFlash('邮件服务已关闭,请与管理员联系!','tip/tip_uc',array('t'=>'error'));
					}else{
						//send email;
						$resetlink = Router::url('/',true).'Users_reset.html?code='.encodeReset($userInfo['User']['id'],$email);
						App::uses('CakeEmail', 'Network/Email');
						$Email = new CakeEmail();
						$Email->config(array(
								'transport' => 'Smtp',
								'from' => array($config['Setting']['mail_account'] => $config['Setting']['mail_name']),
								'host' => $config['Setting']['mail_smtp'],
								'port' => $config['Setting']['mail_port'],
								'timeout' => 30,
								'username' => $config['Setting']['mail_account'],
								'password' => $config['Setting']['mail_password'],
								'client' => null,
								'log' => false,
								//'charset' => 'utf-8',
								//'headerCharset' => 'utf-8',
						));
						$Email->viewVars(array('link' => $resetlink,'email'=>$email));
						$Email->template('forget', '')
						->emailFormat('html')
						->to($email)->subject('密码重置--秦文票务')
						->send();
						$this->redirect(citylink('Users','valid'));
					}
				}else{
					$this->Session->setFlash('您输入的邮箱不存在!','tip/tip_uc',array('t'=>'error'));
				}
			}
		}
		$this->set('seo_title','忘记密码');
		$this->set('seo_keywords',false);
		$this->set('seo_description',false);
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}
	
	public function valid(){
		$this->set('seo_title','找回密码');
		$this->set('seo_keywords',false);
		$this->set('seo_description',false);
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}
	
	public function reset(){
		if (!isset($this->request->query['code'])) {
			$this->Session->setFlash('链接已失效，请重新申请!','tip/tip_uc',array('t'=>'error'));
			$this->redirect(citylink('Users','forget'));
		}else{
			$param = decodeReset($this->request->query['code']);
			if (!isset($param['email'])) {
				$this->Session->setFlash('链接已失效，请重新申请!','tip/tip_uc',array('t'=>'error'));
				$this->redirect(citylink('Users','forget'));
			}
			$email = $param['email'];
			$uid = $param['uid'];
		}
		
		if(isset($param['uid'])){
			if ($this->request->is(array('post', 'put'))) {
				if($this->request->data['User']['password'] == '' ||$this->request->data['User']['confirm_password'] == ''){
					$this->Session->setFlash('密码不能为空!','tip/tip_uc',array('t'=>'error'));
				}else if($this->request->data['User']['password'] != $this->request->data['User']['confirm_password']){
					$this->Session->setFlash('确认密码不正确!','tip/tip_uc',array('t'=>'error'));
				}else {
					//---------------------------------------------------------------------------------修改密码
						$data['User']['id'] = $uid;
						$data['User']['password'] = $this->request->data['User']['password'];
						if($this->User->editPassword($data)){
							$this->Session->delete('forget.email');//删除session
							$this->redirect(citylink('Users','reseted'));
						}else{
							$this->Session->setFlash('修改密码失败，请重试!','tip/tip_uc',array('t'=>'error'));
						}
				}
			}
		}else{
			$this->Session->setFlash('请先输入邮箱!','tip/tip_uc',array('t'=>'error'));
			$this->redirect(citylink('Users','forget'));
		}
		$this->set('seo_title','密码重置');
		$this->set('seo_keywords',false);
		$this->set('seo_description',false);
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}
	
	public function reseted() {
		$this->set('seo_title','密码重置成功');
		$this->set('seo_keywords',false);
		$this->set('seo_description',false);
		$this->set('seo_title_ext','【秦文票务演出订票官网】');
	}
	
}
